package com.sgl.blog.controller;

import com.sgl.blog.pojo.BlogAccount;
import com.sgl.blog.service.AccountService;
import com.sgl.blog.util.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @标题： FileController
 * @内容：
 * @作者： 宋志豪
 */
@Controller
@Slf4j
@RequestMapping("file")
public class FileController {

    @Value("${upload.picture.filePath}")
    private String filePath;
    @Value("#{T(org.thymeleaf.util.StringUtils).substringBefore('${upload.picture.visitPath}','**')}")
    private String visitPath;


    @Resource
    private AccountService accountService;

    @PostMapping("fileUpload")
    public String fileUpload(@RequestParam("file")MultipartFile file, HttpSession session, Model model) {
        BlogAccount account = (BlogAccount) session.getAttribute("account");
        if (account != null){
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            fileName = CodeUtils.getUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            account.setAccountProfilePhoto(visitPath + fileName);
            accountService.updateAccount(account);
            model.addAttribute("msg",3);
            session.setAttribute("account",account);
        }
        return "blog/list";
    }

}
